﻿using DevExpress.XtraEditors;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace BW.Mes.WinForms.WareHouse
{
    public partial class UpdateStorageForm : DevExpress.XtraEditors.XtraForm
    {

        private long _storageId; // 存储货架ID
        public UpdateStorageForm()
        {
            InitializeComponent();

            

        }
        // 带ID参数的构造函数
        public UpdateStorageForm(long storageId)
        {
            InitializeComponent();
            _storageId = storageId;
            this.textEdit1.ReadOnly = true;
        }

        private void UpdateStorageForm_Load(object sender, EventArgs e)
        {
            // 加载仓库下拉数据
            LoadWareHouseData();

            // 加载存储货架数据
            LoadStorageData();
        }







        /// <summary>
        /// 关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton1_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void simpleButton2_Click(object sender, EventArgs e)
        {
            UpdateStorage();
        }


        // 加载货架数据
        private async void LoadStorageData()
        {
            try
            {
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri("http://120.26.197.100:8022/");
                    var response = await client.GetAsync($"T3/Storage/GetModelStorage?Id={_storageId}");

                    if (response.IsSuccessStatusCode)
                    {
                        var jsonContent = await response.Content.ReadAsStringAsync();
                        
                        // 处理API返回的数据结构
                        var jsonObject = Newtonsoft.Json.Linq.JObject.Parse(jsonContent);
                        StorageItem storage = null;
                        
                        // 检查是否有data字段
                        if (jsonObject["data"] != null)
                        {
                            string dataJson = jsonObject["data"].ToString();
                            var items = JsonConvert.DeserializeObject<StorageItem>(dataJson);
                            if (items != null )
                            {
                                storage = items;
                            }
                        }
                        else
                        {
                            // 直接尝试反序列化
                            storage = JsonConvert.DeserializeObject<StorageItem>(jsonContent);
                        }
                        
                        if (storage != null)
                        {
                            // 回显数据到控件
                            textEdit1.Text = storage.StorageCoding;
                            textEdit2.Text = storage.StorageName;
                            textEdit3.Text = storage.StorageDescribe;

                            // 保存仓库ID，以便在下拉框数据加载后设置
                            _selectedWareHouseId = storage.WareHouseId;

                            // 如果仓库数据已加载，则设置选中值
                            SetSelectedWareHouse();
                        }
                    }
                    else
                    {
                        XtraMessageBox.Show("获取货架数据失败:" + response.ReasonPhrase, "错误");
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show("加载货架数据出错:" + ex.Message, "错误");
            }
        }

        private long _selectedWareHouseId = 0; // 保存选中的仓库ID

        /// <summary>
        /// 设置选中的仓库
        /// </summary>
        private void SetSelectedWareHouse()
        {
            if (_selectedWareHouseId > 0)
            {
                // 检查使用的是哪种控件
                if (gridLookUpEdit1 != null && gridLookUpEdit1.Properties.DataSource != null)
                {
                    gridLookUpEdit1.EditValue = _selectedWareHouseId;
                }
                // 如果是使用comboBoxEdit1，则取消注释下面的代码
                // else if (comboBoxEdit1 != null && comboBoxEdit1.Properties.DataSource != null)
                // {
                //     comboBoxEdit1.EditValue = _selectedWareHouseId;
                // }
            }
        }

        /// <summary>
        /// 加载仓库数据
        /// </summary>
        private async void LoadWareHouseData()
        {
            try
            {
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri("http://120.26.197.100:8022/");
                    var response = await client.GetAsync("T3/Storage/GetAllWareHouse");

                    if (response.IsSuccessStatusCode)
                    {
                        var jsonContent = await response.Content.ReadAsStringAsync();
                        var jsonObject = JsonConvert.DeserializeObject<dynamic>(jsonContent);

                        if (jsonObject["pageDatas"] != null)
                        {
                            var dataJson = jsonObject["pageDatas"].ToString();
                            var warehouses = JsonConvert.DeserializeObject<List<WareHouseItem>>(dataJson);

                            if (warehouses != null && warehouses.Count > 0)
                            {
                                // 设置数据源
                                gridLookUpEdit1.Properties.DataSource = warehouses;
                                gridLookUpEdit1.Properties.DisplayMember = "WarehouseName";
                                gridLookUpEdit1.Properties.ValueMember = "Id";

                                // 设置选中值
                                SetSelectedWareHouse();
                            }
                        }
                    }
                    else
                    {
                        XtraMessageBox.Show("获取仓库数据失败:" + response.ReasonPhrase, "错误");
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show("加载仓库数据出错:" + ex.Message, "错误");
            }
        }

        /// <summary>
        /// 更新货架数据
        /// </summary>
        private async void UpdateStorage()
        {
            try
            {
                // 验证数据
                if (string.IsNullOrEmpty(textEdit1.Text))
                {
                    XtraMessageBox.Show("请输入货架编码", "提示");
                    return;
                }

                if (string.IsNullOrEmpty(textEdit2.Text))
                {
                    XtraMessageBox.Show("请输入货架名称", "提示");
                    return;
                }

                if (gridLookUpEdit1.EditValue == null)
                {
                    XtraMessageBox.Show("请选择所属仓库", "提示");
                    return;
                }

                var model = new StorageUpdateInput
                {
                    Id = _storageId,
                    StorageCoding = textEdit1.Text,
                    StorageName = textEdit2.Text,
                    WareHouseId = Convert.ToInt64(gridLookUpEdit1.EditValue),
                    StorageDescribe = textEdit3.Text
                };

                // 调用API更新数据
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri("http://120.26.197.100:8022/");
                    var json = JsonConvert.SerializeObject(model);
                    var content = new StringContent(json, Encoding.UTF8, "application/json");
                    var response = await client.PutAsync("T3/Storage/UpdateStorage", content);

                    if (response.IsSuccessStatusCode)
                    {
                        XtraMessageBox.Show("更新成功", "提示");
                        this.DialogResult = DialogResult.OK;
                        this.Close();
                    }
                    else
                    {
                        XtraMessageBox.Show("更新失败:" + response.ReasonPhrase, "错误");
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show("更新数据出错:" + ex.Message, "错误");
            }
        }







        /// <summary>
        /// 仓库数据模型
        /// </summary>
        public class WareHouseItem
        {
            public long Id { get; set; }
            public string WarehouseName { get; set; }
        }

        /// <summary>
        /// 货架数据模型
        /// </summary>
        public class StorageItem
        {
            public long Id { get; set; }
            public string StorageCoding { get; set; }
            public string StorageName { get; set; }
            public long WareHouseId { get; set; }
            public string StorageDescribe { get; set; }
        }

        /// <summary>
        /// 更新货架输入模型
        /// </summary>
        public class StorageUpdateInput
        {
            public long Id { get; set; }
            public string StorageCoding { get; set; }
            public string StorageName { get; set; }
            public long WareHouseId { get; set; }
            public string StorageDescribe { get; set; }
        }












    }
}